#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdlib>
// 父进程读取，子进程写入
using namespace std;
int main()
{
    // 1.创建管道
    int fds[2] = {0};
    int n = pipe(fds);
    if (n != 0)
    {
        cerr << "pipe error" << endl;
    }
    // 2.创建子进程
    pid_t id = ::fork();
    if (id < 0)
    {
        cerr << "fork error" << endl;
        return 2;
    }
    else if (id == 0)
    {
        // 子进程
        // 3.关闭不需要的fd,关闭read
        ::close(fds[0]);
        int cnt=0;
        int total=0;
        while(true)
        {
            string message="h";
            // message+=to_string(getpid());
            // message+=", ";
            // message+=to_string(cnt);
            total+=::write(fds[1],message.c_str(),message.size());
            cnt++;
            // sleep(1);
            cout<<"total: "<<total<<endl;
        }
        exit(0);
    }
    else
    {
        // 父进程
        // 3.关闭不需要的fd,关闭write
        ::close(fds[1]);
        char buffer[1024];
        while(true)
        {
            sleep(100);
            ssize_t n=::read(fds[0],buffer,1024);
            if(n>0)
            {
                buffer[n]=0;
            }
            cout<<"child->child,message:"<<buffer<<endl;
        }
        pid_t rid = waitpid(id, nullptr, 0);
        cout << "father wait child success:" << rid << endl;
    }
    return 0;
}